package sdfs;
import sdfs.client.SimpleDistributedFileSystem;
import sdfs.namenode.SDFSFileChannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

public class Main {

    private static final String GOOD = " GOOD !";
    private static final String WONDER = "You are the best !";

    /**
     *  at the beginning you should run the DataNodeServer and  the NameNodeServer.
     */
    public static void main(String[] args) throws Exception {
        try{
            //do not make file in root , but you can mkdir in root
            //for examples: this is a  wrong uri -> sdfs://127.0.0.1:8888/test
            SimpleDistributedFileSystem sdfs =
                    new SimpleDistributedFileSystem(InetSocketAddress.createUnresolved("127.0.0.1",9999),16);

//           // test create file and write file
//            SDFSFileChannel sdfsFileChannel1 = sdfs.create("sdfs://127.0.0.1:8888/foo/test2");
//            sdfsFileChannel1.write(ByteBuffer.wrap(WONDER.getBytes()));
//            sdfsFileChannel1.close();
//            sdfsFileChannel1.flush();

//            //test open file and read file
            SDFSFileChannel sdfsFileChannel2=sdfs.openReadWrite("sdfs://127.0.0.1:8888/foo/test1");

            ByteBuffer buffer = ByteBuffer.allocate((int)sdfsFileChannel2.size());
            sdfsFileChannel2.read(buffer);
            buffer.flip();//必须flip, 不然remain < length 出异常
            byte [] bytes = new byte[(int)sdfsFileChannel2.size()];
            buffer.get(bytes);
            System.out.println(new String(bytes));
            sdfsFileChannel2.close(); // save nameNode
            sdfsFileChannel2.flush();

            //test open file and write file

            SDFSFileChannel sdfsFileChannel3=sdfs.openReadWrite("sdfs://127.0.0.1:8888/foo/test1");
            sdfsFileChannel3.write(ByteBuffer.wrap(GOOD.getBytes()));
            sdfsFileChannel3.close();
            sdfsFileChannel3.flush();

            //sdfs.mkdir("sdfs://127.0.0.1:8888/too");  //ok
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
